{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 穷举法实现 0-1 背包问题\n",
    "\n",
    "算法步骤：\n",
    "1. 初始化 $V\\gets 0$, $mask\\gets [0,0,0,..]$ \n",
    "2. 生成长度为 n 的所有二进制序列, 代表是否放入该物品.\n",
    "3. 遍历每个序列 seq, 计算该序列的 $V',W'$, 如果 $V' > V \\ and \\ W'\\leq C$, 则 $V\\gets V',mask\\gets seq$\n",
    "4. 遍历结束输出 V, mask\n",
    "\n",
    "时间复杂度：$O(n2^n)$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基本设置\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[15] [70] [4, 13, 2, 18, 3, 3, 4, 16, 8, 17, 5, 1, 20, 2, 14] [21, 1, 3, 11, 13, 16, 16, 20, 21, 11, 15, 7, 10, 3, 19]\n"
     ]
    }
   ],
   "source": [
    "# 数据读取\n",
    "import re\n",
    "def LoadData(path):\n",
    "    '''\n",
    "    数据读取。\n",
    "    Input:\n",
    "    - path: 数据路径.\n",
    "    \n",
    "    Return:\n",
    "    - cache: a list contains (n,c,w,v)\n",
    "    '''\n",
    "    cache = []\n",
    "    with open(path,'r') as f:  \n",
    "         for i in range(4):\n",
    "            x = re.findall(r'\\d+',f.readline())\n",
    "            x = [int(i) for i in x]\n",
    "            cache.append(x)\n",
    "    return cache\n",
    "    \n",
    "path = 'test3.txt'\n",
    "n,c,w,v = LoadData(path)\n",
    "print(n,c,w,v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def GenSeq(n):\n",
    "    '''\n",
    "    生成长度 n 的所有二进制数.\n",
    "    Input:\n",
    "    - n: 正整数 n.\n",
    "    \n",
    "    Return:\n",
    "    - seqs: 所有二进制数列表.\n",
    "    '''\n",
    "    seqs = [] \n",
    "    for i in range(2**n):\n",
    "        x = list('{i:0>{n}b}'.format(i=i, n=n))\n",
    "        x = np.array([int(i) for i in x]) \n",
    "        seqs.append(x)\n",
    "    return seqs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "154\n",
      "[1 0 1 0 1 1 1 1 1 0 1 1 0 1 1]\n"
     ]
    }
   ],
   "source": [
    "# 使用遍历法求解\n",
    "def Exhaustion(n, c, w, v):\n",
    "    '''\n",
    "    使用遍历法求解 0-1 背包问题.\n",
    "    Input:\n",
    "    - n: the number of objects.\n",
    "    - c: the capacity of bag.\n",
    "    - w: the weights of objects.\n",
    "    - v: the value of objects.\n",
    "    \n",
    "    Return:\n",
    "    - mask: which object put in bag.\n",
    "    - values: the largest value.\n",
    "    '''\n",
    "    values = 0\n",
    "    mask = np.zeros(n)\n",
    "    # 数据处理\n",
    "    n = n[0]\n",
    "    c = c[0]\n",
    "    w = np.array(w)\n",
    "    v = np.array(v)\n",
    "    # 生成长为 n 的所有二进制数\n",
    "    seqs = GenSeq(n)\n",
    "    for seq in seqs:\n",
    "        weight = np.sum(w * seq)\n",
    "        value =  np.sum(v * seq)\n",
    "        if value > values and weight <=c:\n",
    "            values = value\n",
    "            mask = seq\n",
    "    return values, mask\n",
    "\n",
    "values, mask = Exhaustion(n,c,w,v)\n",
    "print(values)\n",
    "print(mask)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "torch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
